/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import me.zhengjie.exception.BizException;
import me.zhengjie.modules.pay.enums.StatusEnum;
import me.zhengjie.modules.shop.domain.Product;
import me.zhengjie.modules.shop.domain.ProductCart;
import me.zhengjie.modules.shop.domain.ProductKind;
import me.zhengjie.modules.shop.domain.resp.MyCartListResp;
import me.zhengjie.modules.shop.mapper.ProductKindMapper;
import me.zhengjie.modules.shop.mapper.ProductMapper;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.shop.service.ProductCartService;
import me.zhengjie.modules.shop.domain.vo.ProductCartQueryCriteria;
import me.zhengjie.modules.shop.mapper.ProductCartMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import me.zhengjie.utils.PageResult;

import static me.zhengjie.modules.biz.domain.enums.ErrorCode.BODY_NOTNULL;
import static me.zhengjie.modules.biz.domain.enums.ErrorCode.PRODUCT_NOT_EXIST;
import static me.zhengjie.modules.pay.enums.StatusEnum.CART_AWAIT_DELETE;
import static me.zhengjie.modules.pay.enums.StatusEnum.CART_SHOW;

/**
* @description 服务实现
* @author yiwe.he
* @date 2024-04-12
**/
@Service
@RequiredArgsConstructor
public class ProductCartServiceImpl extends ServiceImpl<ProductCartMapper, ProductCart> implements ProductCartService {

    private final ProductCartMapper productCartMapper;
    private final ProductMapper productMapper;
    private final ProductKindMapper productKindMapper;

    @Override
    public PageResult<MyCartListResp> queryAll(ProductCartQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(productCartMapper.list(criteria, page));
    }

    @Override
    public List<ProductCart> queryAll(ProductCartQueryCriteria criteria){
        return productCartMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(ProductCart resources) throws BizException {
        // 前端经常给错数据，自己查一遍最安全
        Product product = productMapper.selectById(resources.getPId());
        ProductKind kind = productKindMapper.selectById(resources.getKId());
        if(product == null || kind == null){
            throw new BizException(PRODUCT_NOT_EXIST.getCode(),PRODUCT_NOT_EXIST.getMessage());
        }
        resources.setCover(product.getCover());
        resources.setPrice(kind.getPrice());
        resources.setName(product.getName());
        resources.setIntro(product.getIntro());
        resources.setCreateTime(LocalDateTime.now());
        return save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProductCart resources) {
        ProductCart productCart = getById(resources.getId());
        productCart.copy(resources);
        saveOrUpdate(productCart);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteAll(List<Long> ids) {
        return removeBatchByIds(ids);
    }

    @Override
    public void download(List<ProductCart> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProductCart productCart : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("user_id", productCart.getUserId());
            map.put("商品id", productCart.getPId());
            map.put("规格id", productCart.getKId());
            map.put("商品名称", productCart.getName());
            map.put("商品封面", productCart.getCover());
            map.put("商品简介", productCart.getIntro());
            map.put("数量", productCart.getNum());
            map.put("单价", productCart.getPrice());
            map.put("创建时间", productCart.getCreateTime());
            map.put("购物车状态【0：展示 1：待删除】", productCart.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Boolean callBack(ProductCartQueryCriteria criteria) throws BizException {
        if(criteria == null || criteria.getPayStatus() == null || criteria.getUserId() == null){
            throw new BizException(BODY_NOTNULL.getCode(),BODY_NOTNULL.getMessage());
        }
        // 支付失败，展示购物车订单
        if(criteria.getPayStatus() == CART_SHOW.getCode()){
            return this.update(new UpdateWrapper<ProductCart>().eq("user_id",criteria.getUserId()).set("status", StatusEnum.CART_SHOW.getCode()));
        }
        // 支付成功，删除购物车订单
        if(criteria.getPayStatus() == CART_AWAIT_DELETE.getCode()){
            productCartMapper.delete(new QueryWrapper<ProductCart>().eq("user_id",criteria.getUserId()).eq("status",CART_AWAIT_DELETE.getCode()));
        }
        return true;
    }
}